{% extends "auth/base.html" %}

{% block title %}角色管理 - FlaskWeb{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="fas fa-user-tag me-2"></i>角色管理
    </h2>
    <div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal">
            <i class="fas fa-plus me-1"></i>添加角色
        </button>
    </div>
</div>

<div class="card shadow">
    <div class="card-header">
        <h5 class="mb-0">角色列表</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>角色名称</th>
                        <th>描述</th>
                        <th>权限</th>
                        <th>用户数量</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for role in roles %}
                    <tr>
                        <td>{{ role.id }}</td>
                        <td>
                            <span class="badge bg-primary">{{ role.name }}</span>
                        </td>
                        <td>{{ role.description or '-' }}</td>
                        <td>
                            {% for permission in role.permissions %}
                            <span class="badge bg-secondary me-1">{{ permission.name }}</span>
                            {% endfor %}
                        </td>
                        <td>{{ role.users|length }}</td>
                        <td>{{ role.created_at.strftime('%Y-%m-%d') if role.created_at else '-' }}</td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary edit-role" data-role-id="{{ role.id }}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-info manage-permissions" data-role-id="{{ role.id }}">
                                    <i class="fas fa-key"></i>
                                </button>
                                {% if role.name != 'admin' %}
                                <button type="button" class="btn btn-sm btn-outline-danger delete-role" data-role-id="{{ role.id }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加角色模态框 -->
<div class="modal fade" id="addRoleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addRoleForm">
                    <div class="mb-3">
                        <label for="roleName" class="form-label">角色名称</label>
                        <input type="text" class="form-control" id="roleName" required>
                    </div>
                    <div class="mb-3">
                        <label for="roleDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="roleDescription" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="rolePermissions" class="form-label">权限</label>
                        <select class="form-select" id="rolePermissions" multiple>
                            {% for permission in all_permissions %}
                            <option value="{{ permission.id }}">{{ permission.name }} - {{ permission.description }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">按住Ctrl键可选择多个权限</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveRoleBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 管理权限模态框 -->
<div class="modal fade" id="managePermissionsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">管理角色权限</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="managePermissionsForm">
                    <div class="mb-3">
                        <label for="rolePermissionsList" class="form-label">权限</label>
                        <select class="form-select" id="rolePermissionsList" multiple>
                            {% for permission in all_permissions %}
                            <option value="{{ permission.id }}">{{ permission.name }} - {{ permission.description }}</option>
                            {% endfor %}
                        </select>
                        <div class="form-text">按住Ctrl键可选择多个权限</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="savePermissionsBtn">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 添加角色
    document.getElementById('saveRoleBtn').addEventListener('click', function() {
        // 构建数据对象
        const roleData = {
            name: document.getElementById('roleName').value,
            description: document.getElementById('roleDescription').value,
            permissions: Array.from(document.getElementById('rolePermissions').selectedOptions).map(option => option.value)
        };
        
        // 发送AJAX请求
        fetch('{{ url_for("api.create_role") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(roleData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('addRoleModal'));
                modal.hide();
                
                // 显示成功消息
                alert('角色添加成功');
                
                // 刷新页面
                window.location.reload();
            } else {
                alert('添加角色失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('添加角色失败');
        });
    });
    
    // 管理权限
    let currentRoleId = null;
    
    document.querySelectorAll('.manage-permissions').forEach(button => {
        button.addEventListener('click', function() {
            currentRoleId = this.getAttribute('data-role-id');
            
            // 获取角色当前权限
            fetch(`{{ url_for("api.get_role_permissions") }}?role_id=${currentRoleId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 设置选中的权限
                    const permissionsSelect = document.getElementById('rolePermissionsList');
                    Array.from(permissionsSelect.options).forEach(option => {
                        option.selected = data.permissions.includes(parseInt(option.value));
                    });
                    
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('managePermissionsModal'));
                    modal.show();
                } else {
                    alert('获取角色权限失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取角色权限失败');
            });
        });
    });
    
    // 保存权限
    document.getElementById('savePermissionsBtn').addEventListener('click', function() {
        // 获取选中的权限
        const permissionsSelect = document.getElementById('rolePermissionsList');
        const selectedPermissions = Array.from(permissionsSelect.selectedOptions).map(option => option.value);
        
        // 发送AJAX请求
        fetch('{{ url_for("api.update_role_permissions") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                role_id: currentRoleId,
                permissions: selectedPermissions
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('managePermissionsModal'));
                modal.hide();
                
                // 显示成功消息
                alert('权限更新成功');
                
                // 刷新页面
                window.location.reload();
            } else {
                alert('更新权限失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新权限失败');
        });
    });
    
    // 删除角色
    document.querySelectorAll('.delete-role').forEach(button => {
        button.addEventListener('click', function() {
            const roleId = this.getAttribute('data-role-id');
            
            if (confirm('确定要删除此角色吗？此操作不可恢复。')) {
                fetch(`{{ url_for("api.delete_role") }}?role_id=${roleId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('角色删除成功');
                        window.location.reload();
                    } else {
                        alert('删除角色失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除角色失败');
                });
            }
        });
    });
</script>
{% endblock %}